package edu.hnui.shop.controller;

import edu.hnui.shop.commons.BindingResultParseMessageUtils;
import edu.hnui.shop.commons.R;
import edu.hnui.shop.commons.ResultCodeEnum;
import edu.hnui.shop.exception.ShopBusinessException;
import edu.hnui.shop.pojo.User;
import edu.hnui.shop.request.LoginRequest;
import edu.hnui.shop.service.UserService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public R queryById(@PathVariable("id") Integer id){
        User user = userService.findById(id);
        return R.ok().data(user);
    }

    @PostMapping("/login")
    public R login(@RequestBody @Valid LoginRequest loginRequest, BindingResult bindingResult, HttpServletRequest request){
         //判断校验是否存在问题
        if(bindingResult.hasErrors()){
            String message = BindingResultParseMessageUtils.parse(bindingResult);
            throw new ShopBusinessException(ResultCodeEnum.PARAMETER_VALIDATION_ERROR.getCode(),message);
        }
        System.out.println(loginRequest.getTelphone());
        User user= userService.login(loginRequest.getTelphone(), loginRequest.getPwd());
        //将数据存储到session中
        HttpSession session = request.getSession();
        session.setAttribute("LGOIN_USER_MESSAGE",user);

        return R.setResult(ResultCodeEnum.LOGIN_SUCCESS).data(user);
    }

}
